<?php
/*
 * 用户类的基类
 */
class User_Base implements Acl_Role_Interface 
{
	const _CONST_TB_USER_       = 'user_basic';
    const _CONST_TB_VENDOR_     = 'tg_vendor_info';
	protected $_role_id         = NULL;
	protected $_user_id         = NULL;
	protected $_user_info       = NULL;
	protected $_notice          = NULL;

	public function __construct ($uid)
	{
		//
	}

	public static function user_info_by_uid ($uid)
	{
		return self::user_info_by ((int)$uid);
	}

	public static function user_info_by_passport ($passport, $utype)
	{
		return self::user_info_by ($passport, $utype);
	}

	public static function has_user ($passport, $utype)
	{
		$n = DB::select(array('count("uid")', 'count'))
			->from(self::_CONST_TB_USER_)
			->where('passport', '=', $passport)
			->where('utype', '=', $utype)
			->execute()
			->get('count');

		return $n == 1;
	}

	/*
	 * 创建新用户账户
	 */
	public static function create ($info)
	{
		list($insert_id, $rows) = DB::insert(self::_CONST_TB_USER_)
			->columns(array_keys  ($info))
			->values (array_values($info))
			->execute();

		return $insert_id;
	}

	public function get_role_id ()
	{
		return $this->_role_id;
	}

	public function get_user_id ()
	{
		return $this->_user_id;
	}

    public function has_joined_CPS()
    {
        return FALSE;
    }

	/**
	 * 返回用户的名字
	 *
	 * @param	string $name_type : ['nickname', 'realname']
	 * @return  string $name
	 */
	public function get_user_name ($name_type = 'nickname')
	{
		return Arr::get($this->_user_info, $name_type, NULL);
	}

	public function get_user_info ()
	{
		return $this->_user_info;
	}

    public function get_vendor_info ()
    {
        $query = DB::select()
            ->from(self::_CONST_TB_VENDOR_)
            ->where('uid', '=', $this->_user_id)
            ->execute();

        if ($query->valid())
        {
            $info = $query->current();
            $info['type_name'] = Kohana::config('user.vendor.type_name.'.$info['vtype']);
            return $info;
        }
        else
        {
            return NULL;
        }
    }

    public function edit_vendor_info ($info)
    {
        $condition = array('uid' => $this->_user_id);
        if (self::has($condition))
        {
            unset($info['uid']);
            $info['mtime'] = DB::expr('unix_timestamp(current_timestamp())');

            $rows = self::update($info, $condition);
            return $rows > 0;
        }
        else
        {
            $info['ctime'] = DB::expr('unix_timestamp(current_timestamp())');
            $info['mtime'] = $info['ctime'];
            $info['uid']   = $this->_user_id;

            $insert_id = self::insert($info);
            return $insert_id > 0;
        }
    }



	/*
	 * 是否登录
	 *
	 * @return boolean
	 */
	public function is_login ()
	{
		if (is_null($this->_user_id))
			return FALSE;
		else if ($this->_user_id <= 0)
			return FALSE;
		else
			return TRUE;
	}

	/*
	 * Passport 是否登录
	 *
	 * @return boolean
	 */
	public function is_passport_login ()
	{
		$passport = user::passport();

		return empty($passport) ? FALSE : TRUE;
	}


	/*
	 * 是否是商家
	 */
	public function is_merchant ()
	{
		$passport = user::passport();

		if (empty($passport))
			return FALSE;

		if (user::factory($passport, 'merchant'))
			return TRUE;
		else
			return FALSE;
	}

	/*
	 * 用户手机是否绑定
	 *
	 * @reutrn boolean
	 */
	public function mobile_binded ()
	{
		return $this->status('mobile_binded');
	}

	/*
	 * 用户是否当前已经激活
	 *
	 * @return	boolean
	 */
	public function is_activated ()
	{
		return $this->status('activated');
	}

	/*
	 * 获取某状态值
	 *
	 * @param	string  $status_key = ['unactivated', 'activated', 'unverified', 'removed']
	 *
	 * @return	boolean
	 */
	public function status ($status_key = NULL)
	{
		if (empty($this->_user_info) || 
				empty($status_key))
			return FALSE;

        $status = Kohana::config('user.status.'.$status_key);

		if (isset($this->_user_info['status']) && $this->_user_info['status'] == $status)
			return TRUE;
		else
			return FALSE;
	}

	/*
	 * 修改用户属性信息
	 *
	 * @param	array	$update = array(
	 *			'nickname' => string $nickname,
	 *			'realname' => string $realname,
	 *			'mobile'   => string $mobile,
	 *		);
	 *
	 * @return boolean
	 */
	public function set_info ($update)
	{
		$data       = array();
		$valid_keys = array('mobile', 'nickname', 'realname', 'lastlogin_time', 'lastlogin_ip', 'utype');
		foreach ($update as $k => $v)
		{
			if (in_array($k, $valid_keys))
				$data[$k] = $v;
		}

		if (empty($data))
			return FALSE;

		$rows = DB::update(self::_CONST_TB_USER_)
			->set($update)
			->where('uid', '=', $this->_user_id)
			->limit(1)
			->execute();

		return $rows > 0;
	}

	/**
	 * 用户是否有消息通知
	 */
	public function has_notice ()
	{
		if (NULL == $this->_notice)
			$this->_notice = new User_Info_Notice($this->_user_id);

		return $this->_notice->count();
	}

	public function increase_notice ()
	{
		if (NULL == $this->_notice)
			$this->_notice = new User_Info_Notice($this->_user_id);

		return $this->_notice->increase();
	}

	public function clean_notice ()
	{
		if (NULL == $this->_notice)
			$this->_notice = new User_Info_Notice($this->_user_id);

		return $this->_notice->clean();
	}


	public function set_last_login ()
	{
		$time = time();
		$ip   = Request::$client_ip;
		return $this->set_info(array(
				'lastlogin_time' => $time,
				'lastlogin_ip'   => $ip,
			));
	}

	private static function user_info_by ($userid, $utype = NULL)
	{
		$query = DB::select();

		if (is_integer($userid) || is_int($userid))
			$query->where('uid', '=', $userid);
		else
			$query->where('passport', '=', $userid);
				  //->where('utype', '=', $utype);

		$result = $query->from(self::_CONST_TB_USER_)->as_assoc()->execute();
	
		if ($result->count() <= 0)
			return NULL;

		return $result->current();
	}

    protected static function has ($condition)
    {
        $query = DB::select(array('count("uid")', 'count'))
            ->from(self::_CONST_TB_VENDOR_);

        foreach ($condition as $k => $v)
            $query->where($k, '=', $v);

        $count = $query->execute()->get('count');
        return $count > 0;
    }

    protected static function update ($info, $where)
    {
        $query = DB::update(self::_CONST_TB_VENDOR_)
            ->set($info);

        foreach ($where as $k => $v)
            $query->where($k, '=', $v);

        return $query->limit(1)->execute();
    }

    protected static function insert($info)
    {
        list($insert_id, $rows) = DB::insert(self::_CONST_TB_VENDOR_)
            ->columns (array_keys($info))
            ->values  (array_values($info))
            ->execute();

        return $insert_id;
    }

}
